//
//  ApplyPayManager.m
//  CoolTalk
//
//  Created by wulanzhou on 15/7/23.
//  Copyright (c) 2015年 BreazeMago. All rights reserved.
//

#import "ApplePayManager.h"
#import "IAPHelper.h"
#import "AlertHelper.h"


#define Tag_GetProductErro 200

@interface ApplePayManager ()<IAPHelperProtocal>{
    UIAlertView *_allert;
    NSInteger                    _requestCount;
    SERVER_STATE_TYPE   _serverStateType;//服务器状态
}
@property(nonatomic,copy)NSString    *appBuyMoney;//用户目前选择的金额
@property (nonatomic,copy) void (^ApplyPayFinishedBlock) (BOOL success,NSString *errCode);
@end

@implementation ApplePayManager


- (void)dealloc{
    
    if ([[IAPHelper sharedInstance].products count]>0) {
        [[IAPHelper sharedInstance].products removeAllObjects];
    }
    [IAPHelper sharedInstance].iapDelegate =nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init{
    if (self=[super init]) {
        

        //添加官方充值的相关监听
        [IAPHelper sharedInstance].iapDelegate = self;
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(productPurchased:)
                                                     name:kProductPurchasedNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector: @selector(productPurchaseFailed:) name:kProductPurchaseFailedNotification object: nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(successRecharge:)
                                                     name:kSucceedRechargeNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(failRecharge:)
                                                     name:kFailedRechargeNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(transactionStatePurchasing:) name:kTransactionStatePurchasing
                                                   object:nil];
    }
    return self;
}

/**
 *  支付完成回调
 *
 *  @param finished
 */
- (void)setPayApplyCompleted:(void(^)(BOOL success,NSString *errCode))finished{
    self.ApplyPayFinishedBlock=finished;
}






/**
 *  开始苹果支付
 *
 *  @param moneyStr  支付金额
 */
- (void)startPayWithMoneyStr:(NSString*)moneyStr{
    _requestCount=0;
    _serverStateType = GOODTYPE;
    [self buyProductWithMoneyStr:moneyStr];
}

#pragma mark -属性重写
- (void)setAppProductIDArray:(NSArray *)product{
    if (_appProductIDArray!=product) {
        _appProductIDArray=product;
        [IAPHelper sharedInstance].appProductIDArray=product;
    }
}

- (void)setOrderNo:(NSString *)orderNumber{
    if (_orderNo!=orderNumber) {
        _orderNo=orderNumber;
        [IAPHelper sharedInstance].payOrderNo=orderNumber;
    }
}


#pragma mark -私有方法
/**
 *  准备购买
 *
 *  @param money 购买价格
 */
- (void)buyProductWithMoneyStr:(NSString *)money
{
    [self transactionStatePurchasing:nil];
    self.appBuyMoney = money;
    if(_serverStateType != GOODTYPE)
    {
        [NSThread detachNewThreadSelector:@selector(waitServetState)
                                 toTarget:self
                               withObject:nil];
        
    }
    else
    {
        [self trueBuyProductWithMoneyStr:money];
        
    }
}
/**
 *  判断服务器连接状态
 */
- (void)waitServetState
{
    while (_serverStateType!= GOODTYPE)
    {
        if(_serverStateType == FAILTYPE)
        {
            [self performSelectorOnMainThread:@selector(serverStateFailTip)
                                   withObject:nil
                                waitUntilDone:NO];
            return;
        }
        sleep(2);
        
    }
    [self performSelectorOnMainThread:@selector(trueBuyProductWithMoneyStr:)
                           withObject:self.appBuyMoney
                        waitUntilDone:NO];
    
    
}
/**
 *  服务器无法连接
 */
- (void)serverStateFailTip
{
    if(_allert){
        [_allert dismissWithClickedButtonIndex:0 animated:NO];
        _allert = nil;
    }
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"网络错误" message:@"请稍后再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}
/**
 *  购买的ui表示
 *
 *  @param notification
 */
- (void)transactionStatePurchasing:(NSNotification *)notification
{
    if(_allert){
        [_allert dismissWithClickedButtonIndex:0 animated:NO];
    }
    _allert = [[UIAlertView alloc] initWithTitle:@"购买"
                                         message:@"链接中..."
                                        delegate:self
                               cancelButtonTitle:nil
                               otherButtonTitles:nil];
    [_allert show];
    //self.rechageTable.userInteractionEnabled = NO;
}

#pragma mark - IAPHelperProtocal
/**
 *  苹果请求产品成功
 *
 *  @param aFlag  YES表示成功 NO失败
 *  @param aError 失败原因
 */
-( void)getProductsWithResultSuccess:(BOOL)aFlag error:(NSError *)aError
{
    if (aFlag)
    {
        if ([ self.appBuyMoney length]>0)
        {
            [self trueBuyProductWithMoneyStr: self.appBuyMoney];
        }
    }
    else
    {
        [self productsRequestFailedWithErro:aError];
    }
    
}

/**
 *  苹果请求产品失败
 *
 *  @param aError
 */
- (void)productsRequestFailedWithErro:(NSError *)aError
{
    
    NSLog(@"无法链接到itunes,原因：%@",aError.description);
    
    if(_allert){
        [_allert dismissWithClickedButtonIndex:0 animated:NO];
    }
    /*
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"无法链接到itunes"
                                                    message:[aError localizedDescription]
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"再试一次", nil] ;
    alert.tag = Tag_GetProductErro;
    [alert show];
     */
    
    [AlertHelper showAlertWithTitle:@"无法链接到itunes" message:[aError localizedDescription] cancelTitle:@"取消" cancelAction:^{
        self.appBuyMoney = @"";
    } confirmTitle:@"再试一次" confirmAction:^{
        [[IAPHelper sharedInstance] requestProducts];
    }];
    
    //self.rechageTable.userInteractionEnabled = YES;
    
}



/**
 *  开始请求产品
 *
 *  @param money 购买价格
 */
- (void)trueBuyProductWithMoneyStr:(NSString *)money
{
    NSArray *productsArr = [IAPHelper sharedInstance].products;
    if ([productsArr count] == 0) {
        @synchronized([IAPHelper sharedInstance])
        {
            if ([productsArr count] == 0) {
                self.appBuyMoney = money ;
                _requestCount++;
                NSLog(@"%ld",(long)_requestCount);
                if(_requestCount>=3)
                {
                    self.appBuyMoney = @"";
                    if(_allert){
                        [_allert dismissWithClickedButtonIndex:0 animated:NO];
                        _allert = nil;
                    }
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"无法链接到itunes" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
                    [alert show];
                    //self.rechageTable.userInteractionEnabled = YES;
                    
                    return;
                }
                [[IAPHelper sharedInstance] requestProducts];
                return;
            }
        }
    }
    
    [self realy_buyProductWithMoneyStr:money];
}


/**
 *  正在开始购买
 *
 *  @param money  购买价格
 */
-(void)realy_buyProductWithMoneyStr:(NSString *)money{
    
    for (SKProduct *product in [IAPHelper sharedInstance].products)
    {
        
        NSLog(@"localizedDescription =%@",product.localizedDescription);
        NSLog(@"localizedTitle =%@",product.localizedTitle);
        NSLog(@"price =%@",product.price);
        NSLog(@"priceLocale =%@",product.priceLocale);
        
        
        NSLog(@"productIdentifier =%@",product.productIdentifier);
        
        
        
        NSLog(@"downloadContentLengths =%@",product.downloadContentLengths);
        NSLog(@"downloadContentVersion =%@",product.downloadContentVersion);
        
        //开始支付
        if ([self.appProductIDArray containsObject:product.productIdentifier]) {
            [[IAPHelper sharedInstance] buyProduct:product];
            return;
        }
        /**
         if([product.productIdentifier compare:[self.appProductIDArray objectForKey:money] options:NSCaseInsensitiveSearch]==NSOrderedSame){
         [[IAPHelper sharedInstance] buyProduct:product];
         return;
         }
         **/
    }
    if(_allert){
        [_allert dismissWithClickedButtonIndex:0 animated:NO];
        _allert = nil;
    }
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"无法链接到itunes" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
    [alert show];
    
    //self.rechageTable.userInteractionEnabled = YES;
}


#pragma mark - iaphelper回调方法
- (void)failRecharge:(NSNotification *)notification
{
    [_allert dismissWithClickedButtonIndex:0 animated:NO];
    _allert = nil;
    //self.rechageTable.userInteractionEnabled = YES;
}
- (void)successRecharge:(NSNotification*)notification
{
    
    if(_allert){
        [_allert dismissWithClickedButtonIndex:0 animated:NO];
        _allert = nil;
    }
    //self.rechageTable.userInteractionEnabled = YES;
}

/**
 *  购买失败通知
 *
 *  @param notification
 */
- (void)productPurchaseFailed:(NSNotification *)notification
{
    [_allert dismissWithClickedButtonIndex:0 animated:NO];
    _allert = nil;
    
    //self.rechageTable.userInteractionEnabled = YES;
    if ([notification.name isEqualToString:kProductPurchaseFailedNotification]) {

    SKPaymentTransaction * transaction = (SKPaymentTransaction *) notification.object;
    
    NSString *erroMsg = nil;
    NSString *title = @"购买";
    switch (transaction.error.code)
    {
            
        case SKErrorPaymentCancelled:
        {
            erroMsg = @"用户取消购买";
            
        }
            break;
        case SKErrorPaymentNotAllowed:
        {
            erroMsg = @"此设备不允许应用程序内购买";
        }
            break;
        default:
        {
            erroMsg = transaction.error.localizedDescription;
            NSLog(@"%@, %ld", transaction.error.localizedDescription, (long)transaction.error.code);
            title = @"购买错误";
        }
            break;
    }
    /* 2.2.8.0
    if (transaction.error.code != -5000) // 密码错误，系统已经有提示了
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:erroMsg
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"OK", nil] ;
        
        [alert show];
    }
    */
    //支付失败的后台通知
    //[PaymentNotifyManager payNotifyWithType:NotifyApplePayType orderNo:self.orderNo payStatus:@"0" completed:nil];
    
    if (self.ApplyPayFinishedBlock) {
        self.ApplyPayFinishedBlock(NO,[NSString stringWithFormat:@"%ld",(long)transaction.error.code]);
    }
    
   
    }
    //self.rechageTable.userInteractionEnabled = YES;
    
}

/**
 *  购买成功通知
 *
 *  @param notification
 */
- (void)productPurchased:(NSNotification *)notification
{
    [_allert dismissWithClickedButtonIndex:0 animated:NO];
    _allert = nil;
    
    NSString *productIdentifier = (NSString *) notification.object;
    NSLog(@"Purchased: %@", productIdentifier);
    /**
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"恭喜你"
                                                    message:@"充值提交成功，请稍后查询余额(可能会有几分钟的延迟)。"
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"确定", nil];
    
    [alert show];
     
     [AlertHelper showAlertWithTitle:@"恭喜你" message:@"充值提交成功，请稍后查询余额(可能会有几分钟的延迟)。" confirmTitle:@"确定" confirmAction:^{
     
     }];
     
     **/
    
    
    //支付成功的后台通知
    //[PaymentNotifyManager payNotifyWithType:NotifyApplePayType orderNo:self.orderNo payStatus:@"1" completed:nil];
    
    if (self.ApplyPayFinishedBlock) {
        self.ApplyPayFinishedBlock(YES,nil);
    }
    
   
    
   
    
    //self.rechageTable.userInteractionEnabled = YES;
    
}

#pragma  mark UIALertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0)
    { // 取消
        [_allert dismissWithClickedButtonIndex:0 animated:NO];
        _allert = nil;
    }
}

@end
